package C036;

/**
 * ClassName: C07
 * Package: C036
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/1/21 17:22
 * @Version 1.0
 * @Since 1.0
 */
public class C07 {
    // 不提交这个类
    public static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }
    public static void main(String[] args) {
        TreeNode treeNode1 = new TreeNode(1);
        TreeNode treeNode2 = new TreeNode(2);
        TreeNode treeNode3 = new TreeNode(3);
        TreeNode treeNode4 = new TreeNode(4);
        TreeNode treeNode5 = new TreeNode(5);
        treeNode1.left = treeNode2;
        treeNode1.right = treeNode3;
        treeNode2.left = treeNode4;
        treeNode3.right = treeNode5;
        System.out.println((serialize(treeNode1)));
        TreeNode deserialize = deserialize(serialize(treeNode1));
        System.out.println(serialize(deserialize));
    }

    // 序列化
    static int MAXLEN = 10001;
    static TreeNode[] queue = new TreeNode[MAXLEN];
    static int r, l;
    public static String serialize(TreeNode root) {
        StringBuilder str = new StringBuilder();
        if(root == null){
            return str.toString();
        }
        l = r = 0;
        queue[r++] = root;
        str.append(root.val + ",");
        int n = 0;
        TreeNode cur ;
        while(l < r) {
            n = r - l;
            for (int i = 0; i < n; i++) {
                cur = queue[l++];

                if(cur.left != null) {
                    queue[r++] = cur.left;
                    str.append(cur.left.val + ",");
                } else {
                    str.append("#,");
                }
                if(cur.right != null) {
                    queue[r++] = cur.right;
                    str.append(cur.right.val + ",");
                } else {
                    str.append("#,");
                }
            }
        }
        return str.toString();
    }


    // 反序列化
    public static TreeNode deserialize(String str) {
        if("".equals(str) || str == null){
            return null;
        }

        int index = 0;
        String[] nodeStr = str.split(",");
        TreeNode root = generate(nodeStr[index ++]);
        r = l = 0;
        queue[r++] = root;
        while(l < r) {
            TreeNode cur = queue[l++];
            cur.left = generate(nodeStr[index ++]);
            cur.right = generate(nodeStr[index ++]);
            if(cur.left != null) {
                queue[r++] = cur.left;
            }
            if(cur.right != null) {
                queue[r++] = cur.right;
            }
        }
        return root;
    }

    private static TreeNode generate(String s) {
        return "#".equals(s) ? null :  new TreeNode(Integer.parseInt(s));
    }
}
